package com.hafu.dao;

import com.hafu.model.KuCun;
import com.hafu.util.DbUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class KuCunDao {
    public ArrayList<KuCun> getKuCunList() {
        ArrayList<KuCun> list = new ArrayList<>();
        //获取连接
        Connection conn = DbUtil.getConn();
        //获取sql
        String sql = "select * from kucun";
        try {
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                int id = resultSet.getInt("id");
                String spname = resultSet.getString("spname");
                int num = resultSet.getInt("num");
                KuCun kuCun1 = new KuCun(id, spname, num);
                list.add(kuCun1);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }
    public KuCun getKuCunBySpName(String spName,Connection coon)throws SQLException{
        String sql="select * from kucun where spname=?";
        PreparedStatement preparedStatement=coon.prepareStatement(sql);
        preparedStatement.setString(1,spName);
        ResultSet resultSet=preparedStatement.executeQuery();
        if (resultSet.next()){
            int id= resultSet.getInt("id");
            String name=resultSet.getString("spname");
            int num=resultSet.getInt("num");
            KuCun kuCun=new KuCun(id,name,num);
            return kuCun;
        }return null;
    }
    public boolean addKuCun(KuCun kuCun,Connection coon)throws SQLException{
        String sql="insert into kucun(spname,num)values(?,?)";
        PreparedStatement preparedStatement=coon.prepareStatement(sql);
        preparedStatement.setString(1,kuCun.getSpname());
        preparedStatement.setInt(2,kuCun.getNum());
        int i=preparedStatement.executeUpdate();
        if (i>0){
            return true;
        }else return false;
    }public boolean updateKuCun(KuCun kuCunBySpName,Connection coon)throws SQLException{
        String sql="update kucun set num=?where spname=?";
        PreparedStatement preparedStatement=coon.prepareStatement(sql);
        preparedStatement.setInt(1,kuCunBySpName.getNum());
        preparedStatement.setString(2, kuCunBySpName.getSpname());
        int i= preparedStatement.executeUpdate();
        if (i>0){
            return true;
        }else return false;
    }
}
